import java.util.PriorityQueue;

class MyTimerTask implements Comparable<MyTimerTask>{
    // 用 runnable 是任务
    private Runnable runnable;
    // long 类型的时间戳
    private long time ;
    // delay 传入的 时间就是 一个 相对的时间 , 获取 现在的绝对时间 + delay 就是 任务执行的时间
    public MyTimerTask(Runnable runnable, long delay) {
        this.runnable = runnable;
        this.time =  System.currentTimeMillis()  + delay;
    }
    // 实现comparable , 用时间做比较
    @Override
    public int compareTo(MyTimerTask o) {
        return (int) (this.time - o.time);
    }

    // 获取时间
    public long getTime(){
        return time;
    }
    // 获取 任务
    public Runnable getRunnable(){
        return runnable;
    }
}



class MyTimer{
     private PriorityQueue<MyTimerTask> queue = new PriorityQueue<>();
     private Object lock = new Object();

     public void schedule(Runnable runnable , long time){
          synchronized (lock){
              queue.offer(new MyTimerTask(runnable,time));
              lock.notify();
          }
     }

     public MyTimer(){
        // 有一个扫描线程
         Thread t = new Thread(()->{
              while (true){
                  synchronized (lock){
                      try {
                      while (queue.isEmpty()){
                              lock.wait();
                      }
                      MyTimerTask task = queue.peek();
                      long curTime = System.currentTimeMillis();
                      if(curTime >= task.getTime()){
                          task.getRunnable().run();
                          queue.poll();
                      }else{
                          lock.wait(task.getTime()-curTime);
                      }
                      } catch (InterruptedException e) {
                      e.printStackTrace();
                      }
                  }

              }
         });
         t.start();
     }

}


public class Test6 {
    public static void main(String[] args) {
       MyTimer myTimer = new MyTimer();
       myTimer.schedule(new Runnable() {
           @Override
           public void run() {
               System.out.println("1000");
           }
       }, 100);
        myTimer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("2000");
            }
        }, 200);
        myTimer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("3000");
            }
        }, 3000);
        myTimer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("4000");
            }
        }, 4000);
        System.out.println("计时器开始");
    }
}
